package ui.swing.model;

import java.util.List;

import javax.swing.table.DefaultTableModel;

import analyse.IndustryItem;
import analyse.IndustrySort;

import data.Constant;
import data.LoadData;
import data.TimeStock;

public class IndustryHeadStockModel extends DefaultTableModel implements Stoppable{

	private static final long serialVersionUID = 4443142888003838110L;
	
	protected static String[] col = new String[]{"industry","averPercent","code","name","curPrice","diffPrice","ratePercent","bat","maxprice","minprice","time","priceSpeed"};
	private boolean run = true;
	private Object[][] datas = new Object[0][col.length];
	
	public IndustryHeadStockModel() {
		super();
		fillValues();
		setDataVector(datas,col);
		Thread th = new Thread(this);
		th.start();
	}
	
	protected List<IndustryItem> getIndustrySort() {
		return IndustrySort.getRateSort2();
	}
	
	private void fillValues(){
		List<IndustryItem> list = getIndustrySort();
		datas = new Object[list.size()*3][col.length];
		try{
			for (int i = 0; i <list.size(); i++) {
				IndustryItem industryItem = list.get(i);
				String[] codes = industryItem.getCode();
				for (int j = 0; j < codes.length; j++) {
					TimeStock ts = LoadData.getTimeStock(codes[j]);
					datas[i*3+j][0] = industryItem.getIndustry();
					datas[i*3+j][1] = industryItem.getAverPercent();
//					datas[i*3+j][2] = industryItem.getSpeed();
					datas[i*3+j][2] = ts.getCode();
					datas[i*3+j][3] = ts.getStockName();
					datas[i*3+j][4] = ts.getCurPrice().toString();
					datas[i*3+j][5] = ts.getCurPrice().subtract(ts.getPreDayPrice()).toString();
					if (ts.getRatePercent().compareTo(Constant.ZERO) > 0) {
						datas[i*3+j][6] = "+" + ts.getRatePercent() + "%";
					} else {
						datas[i*3+j][6] = ts.getRatePercent() + "%";
					}
					datas[i*3+j][7] = ts.getAmountBat().toString();
					datas[i*3+j][8] = ts.getMaxPrice().toString();
					datas[i*3+j][9] = ts.getMinPrice().toString();
					datas[i*3+j][10] = ts.getTime().toString();
					datas[i*3+j][11] = ts.getPriceWive().toString();
				}
			}
		}catch(Exception e){
			fillValues();
		}
		
		if(getRowCount()!=datas.length){
			setDataVector(datas,col);
		}else{
			for (int i = 0; i < datas.length; i++) {
				for (int j = 0; j < datas[i].length; j++) {
					setValueAt(datas[i][j], i, j);
				}
			}
		}
		
	}
	
	public void stop(){
		run = false;
	}
	
	@Override
	public void run() {
		while(run){
//			loadData();
			fillValues();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
